﻿using Newtonsoft.Json.Serialization;
using System.Reflection;

namespace ED.Common.Utils
{
    public class NullToEmptyStringValueProvider : IValueProvider
    {
        private readonly PropertyInfo _memberInfo;

        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _memberInfo = memberInfo;
        }

        public object GetValue(object target)
        {
            object obj = _memberInfo.GetValue(target);
            if (_memberInfo.PropertyType == typeof(string) && obj == null)
            {
                obj = string.Empty;
            }

            if (_memberInfo.PropertyType.IsClass && obj == null)
            {
                try
                {
                    obj = Activator.CreateInstance(_memberInfo.PropertyType);
                    _memberInfo.SetValue(target, obj);
                }
                catch
                {
                }
            }

            return obj;
        }

        public void SetValue(object target, object value)
        {
            _memberInfo.SetValue(target, value);
        }
    }
}
